package v3

import (
	"time"

	nproto "nggs/network/protocol"
)

type MessageBroker struct {
	lastRecvTimestamps map[MessageID]time.Time
	recvTimes          map[MessageID]int
}

func NewMessageBroker() *MessageBroker {
	b := &MessageBroker{
		lastRecvTimestamps: map[MessageID]time.Time{},
		recvTimes:          map[MessageID]int{},
	}
	return b
}

func (b *MessageBroker) CanAccept(iRecv IMessage) (err error) {
	messageID := iRecv.Head().MessageID

	now := time.Now()
	if lastRecvTimestamp, ok := b.lastRecvTimestamps[messageID]; ok {
		if now.Sub(lastRecvTimestamp) < iRecv.MinInterval() {
			err = &nproto.ErrTooOften{
				MessageID: messageID,
			}
			return
		}
	}
	b.lastRecvTimestamps[messageID] = now

	b.recvTimes[messageID] += 1
	if iRecv.Once() && b.recvTimes[messageID] > 1 {
		err = &nproto.ErrRecvTimesReachMax{
			MessageID: messageID,
		}
		return
	}

	return
}
